import { Request } from '../../../wxParse/request.js';
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        statusBarHeight: getApp().globalData.statusBarHeight,
        rich: '',
        chooseSize: false, //初始模块未被选择
        backheight: '100vh',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.activitId = options.activitId; //活动详情列表id
        this.click = 1; //统计参与按钮的点击次数
        //从抽奖结果服务通知进入
        if (options.SharePrize == 'true') {
            this.setData({
                SharePrize: true,
                background: 'background-color: #ffffff;',
            });
            this.openShow = false;
        } else {
            this.setData({
                background: 'background-color: #ff6666;',
            });
            this.openShow = true;
        }
        //从我的页面 参与活动 我的发布进入
        if (options.ownShow == 'closeTab') {
            this.setData({
                tabBarShow: false,
            });
        } else {
            this.setData({
                tabBarShow: true,
            });
        }
        // console.log(options.activitId);
        //获取活动详情信息接口
        new Request('Activity/GetActivityDetail').request(
            () => {
                return {
                    openid: app.globalData.openid, //用户openid
                    ActivityId: this.activitId, //活动详情列表id
                };
            },
            (res) => {
                if (!res.data.data == '' && res.data.data != null) {
                    //活动内容信息
                    this.setData({
                        ActivityInfo: res.data.data,
                    });
                } else {
                    wx.showToast({
                        title: '参数有误',
                        icon: 'none',
                        duration: 2000,
                    });
                }
            }
        );
        if (app.globalData.openid == '') {
            // 登录
            wx.login({
                success: function (res) {
                    // 发送 res.code 到后台换取 openId, sessionKey, unionId
                    if (res.code) {
                        wx.request({
                            url: 'https://weizhi.darenjian.com/api/pinduo/chou_award/login/login',
                            method: 'POST',
                            data: {
                                code: res.code,
                            },
                            header: {
                                'content-type': 'application/x-www-form-urlencoded',
                                cookie: 'PHPSESSID=' + 1,
                            },
                            success: function (res) {
                                if (res.data.loginCode == 1) {
                                    app.globalData.loginStatus = true; //授权登录
                                    app.globalData.openid = res.data.openid;
                                    app.globalData.userid = res.data.userId; //用户id
                                    app.globalData.userName = res.data.userName; //用户名
                                } else {
                                    app.globalData.loginStatus = false; //未授权登录
                                    app.globalData.openid = res.data.openid;
                                }
                                let openid = res.data.openid;
                                this._GetUserTakeActivity(openid);
                                // this.GotoActivityInfo(); //加载活动详情信息

                                app.globalData.status = res.data.status; //用户登录状态
                                this.setData({
                                    loginStatus: app.globalData.loginStatus,
                                });
                                console.log(app);
                            }.bind(this),
                        });
                    } else {
                        console.log('登录失败！' + res.errMsg);
                    }
                }.bind(this),
            });
        } else {
            this._GetUserTakeActivity(app.globalData.openid);
        }
        //获取活动 参与用户人数列表
        new Request('Activity/GetActivityTakeUserList').request(
            () => {
                return {
                    openid: app.globalData.openid, //用户openid
                    ActivityId: this.activitId, //活动详情列表id
                };
            },
            (res) => {
                if (res.data.data != null) {
                    this.TakeUserList = new Array();
                    //获取用户参与列表
                    res.data.data.map(
                        function (e, n) {
                            //展示只取前5名
                            if (n <= 5) {
                                this.TakeUserList.push(e);
                            }
                        }.bind(this)
                    );
                    this.setData({
                        takeUserList: this.TakeUserList,
                    });
                } else {
                    // wx.showToast({
                    //   title: '快点报名分享活动哟~',
                    //   icon: 'none',
                    //   duration: 2000
                    // });
                }
            }
        );
    },
    /**
     * @param {获取用户是否参与此活动的信息} param
     */
    _GetUserTakeActivity: function (param) {
        //获取用户是否参与此抽奖活动
        if (app.globalData.openid == '') {
            this.UserInfoOpenid = param;
        } else {
            this.UserInfoOpenid = app.globalData.openid;
            this.setData({
                loginStatus: true,
            });
        }

        new Request('Chou/TakeActivity').request(
            () => {
                return {
                    openid: this.UserInfoOpenid, //用户openid
                    ActivityId: this.activitId, //活动详情列表id
                    SelectUserTake: 1, //开启查询结果
                };
            },
            (res) => {
                //获取用户参与状态  -4是代表参与过了
                let UserTakeActivityStatus = res.data.data;
                if (UserTakeActivityStatus == -6) {
                    var StyleAct = 'background-color: #E95750;border: 1rpx solid #FF0000;';
                    var StyleTet = '参与抽奖';
                } else if (UserTakeActivityStatus == -5) {
                    var StyleAct = 'background-color: #999999;border: 1rpx solid #777777;';
                    var StyleTet = '已开奖';
                } else if (UserTakeActivityStatus == -4) {
                    var StyleAct = 'background-color: #66CC00;border: 1rpx solid #669900;';
                    var StyleTet = '已报名';
                } else if (UserTakeActivityStatus == -7) {
                    var StyleAct = 'background-color: #E95750;border: 1rpx solid #FF0000;';
                    var StyleTet = '分享活动';
                } else if (UserTakeActivityStatus == -8) {
                    var StyleAct = 'background-color: #999999;border: 1rpx solid #777777;';
                    var StyleTet = '已结束';
                }
                this.setData({
                    ShowStatusButton: StyleAct,
                    StyleText: StyleTet,
                    UserTakeActivityStatus: res.data.data,
                });
            }
        );
    },
    /**
     *
     * @param {获取暗号 输入框内容} param
     */
    _InputAn: function (param) {
        this.AnHaoText = param.detail.value; //暗号输入内容
    },
    /**
     *
     * @param {参与此活动 | 报名  没有暗号的抽奖按钮} param
     */
    _buttonTakeActivity: function (param) {
        if (param.currentTarget.dataset.take == -4) {
            wx.showToast({
                title: ' 你已报名了',
                icon: 'none',
                duration: 2000,
            });
        } else if (param.currentTarget.dataset.take == -5) {
            wx.showToast({
                title: '已开奖',
                icon: 'none',
                duration: 2000,
            });
        } else if (param.currentTarget.dataset.take == -6) {
            //判断暗号 输入正确的暗号才可以参与抽奖  判断是否有暗号
            if (!this.data.ActivityInfo.activtiyTackCode != '') {
                wx.requestSubscribeMessage({
                    tmplIds: ['klQFw9podMSiQaC-ZFmKQx5LUtUfyy3ICPCyka7SQOc', 'cLL0NK4kh5SkkWREW_brM6TZY6zDbbXSz3Xb4G-Bpj0'],
                    complete: () => {
                        //用户 点击参与活动报名
                        new Request('Chou/TakeActivity').request(
                            () => {
                                return {
                                    openid: app.globalData.openid, //用户openid
                                    ActivityId: this.activitId, //活动详情列表id
                                };
                            },
                            (res) => {
                                if (res.data.data == 1) {
                                    wx.showToast({
                                        title: res.data.msg,
                                        icon: 'none',
                                        duration: 2000,
                                    });
                                    setTimeout(
                                        function () {
                                            //两秒后刷新 按钮 活动页面内容
                                            this.shuaxing();
                                        }.bind(this),
                                        2001
                                    );
                                } else {
                                    wx.showToast({
                                        title: res.data.msg,
                                        icon: 'none',
                                        duration: 2000,
                                    });
                                }
                            }
                        );
                    },
                });
            } else {
                //有暗号的输入
                if (typeof this.AnHaoText != 'undefined' && this.AnHaoText != '') {
                    //正确的暗号
                    if (this.data.ActivityInfo.activtiyTackCode == this.AnHaoText) {
                        wx.requestSubscribeMessage({
                            tmplIds: ['klQFw9podMSiQaC-ZFmKQx5LUtUfyy3ICPCyka7SQOc', 'cLL0NK4kh5SkkWREW_brM6TZY6zDbbXSz3Xb4G-Bpj0'],
                            complete: () => {
                                //用户 点击参与活动报名
                                new Request('Chou/TakeActivity').request(
                                    () => {
                                        return {
                                            openid: app.globalData.openid, //用户openid
                                            ActivityId: this.activitId, //活动详情列表id
                                        };
                                    },
                                    (res) => {
                                        if (res.data.data == 1) {
                                            wx.showToast({
                                                title: res.data.msg,
                                                icon: 'none',
                                                duration: 2000,
                                            });
                                            //关闭暗号显示输入框
                                            this.setData({
                                                ShowCodeBox: false,
                                            });
                                            setTimeout(
                                                function () {
                                                    //两秒后刷新 按钮
                                                    this.shuaxing();
                                                }.bind(this),
                                                2001
                                            );
                                        } else {
                                            wx.showToast({
                                                title: res.data.msg,
                                                icon: 'none',
                                                duration: 2000,
                                            });
                                        }
                                    }
                                );
                            },
                        });
                    } else {
                        wx.showToast({
                            title: '暗号错误',
                            icon: 'none',
                            duration: 2000,
                        });
                    }
                } else {
                    console.log(this.AnHaoText);
                    //开启暗号显示输入框
                    this.setData({
                        ShowCodeBox: true,
                    });
                    if (this.click >= 2) {
                        wx.showToast({
                            title: '请输入暗号',
                            icon: 'none',
                            duration: 2000,
                        });
                    }
                    this.click++;
                }
            }
        } else if (param.currentTarget.dataset.take == -7) {
            wx.showToast({
                title: '将自己的活动分享给好友吧',
                icon: 'none',
                duration: 2000,
            });
            setTimeout(() => {
                let param = {
                    currentTarget: {
                        id: 'fenxiang',
                    },
                };
                this.showshadow(param);
            }, 2001);
        } else if (param.currentTarget.dataset.take == -8) {
            //活动已经结束 查询用户是否获奖 获奖跳转到领取奖品页面
            new Request('Prize/ShowPrizeInfo').request(
                () => {
                    return {
                        openid: app.globalData.openid, //用户openid
                        userId: app.globalData.userid, //用户id
                        ActivityId: this.activitId, //活动详情列表id
                    };
                },
                (res) => {
                    if (res.data.code == 88) {
                        //中奖了
                        wx.navigateTo({
                            url: '/pages/prize/prize?activitId=' + this.activitId,
                        });
                    } else if (res.data.code == -99) {
                        //没有中奖
                        wx.showToast({
                            title: '很遗憾，重在参与！',
                            icon: 'none',
                            duration: 2000,
                        });
                        setTimeout(() => {
                            this.setData({
                                SharePrize: true,
                            });
                        }, 2001);
                    }
                }
            );
        }
    },
    /**
     * 预览用户发布的推广二维码图片
     */
    _previewImage: function (params) {
        let img = params.currentTarget.dataset.image;
        let imgArr = new Array();
        imgArr.push(img);
        wx.previewImage({
            current: imgArr[0], // 当前显示图片的http链接
            urls: imgArr, // 需要预览的图片http链接列表
        });
    },

    /**
     * 刷新 参与报名的 按钮
     */
    shuaxing: function () {
        //获取用户是否参与此抽奖活动
        new Request('Chou/TakeActivity').request(
            () => {
                return {
                    openid: app.globalData.openid, //用户openid
                    ActivityId: this.activitId, //活动详情列表id
                    SelectUserTake: 1, //开启查询结果
                };
            },
            (res) => {
                //获取用户参与状态  -4是代表参与过了
                let UserTakeActivityStatus = res.data.data;
                if (UserTakeActivityStatus == -6) {
                    var StyleAct = 'background-color: #E95750;border: 1rpx solid #FF0000;';
                    var StyleTet = '参与抽奖';
                } else if (UserTakeActivityStatus == -5) {
                    var StyleAct = 'background-color: #999999;border: 1rpx solid #777777;';
                    var StyleTet = '已开奖';
                } else if (UserTakeActivityStatus == -4) {
                    var StyleAct = 'background-color: #66CC00;border: 1rpx solid #669900;';
                    var StyleTet = '已报名';
                } else if (UserTakeActivityStatus == -7) {
                    var StyleAct = 'background-color: #E95750;border: 1rpx solid #FF0000;';
                    var StyleTet = '分享活动';
                } else if (UserTakeActivityStatus == -8) {
                    var StyleAct = 'background-color: #999999;border: 1rpx solid #777777;';
                    var StyleTet = '已结束';
                }
                this.setData({
                    ShowStatusButton: StyleAct,
                    StyleText: StyleTet,
                    UserTakeActivityStatus: res.data.data,
                });
            }
        );
    },
    /**
     * 返回首页
     */
    gohome: function (param) {
        wx.switchTab({
            url: '/pages/home/home',
        });
    },
    /**
     *
     * @param {跳转至用户列表} param
     */
    gotoUserList: function (param) {
        wx.navigateTo({
            url: '/pages/home/good_detail/participate_userlist/participate_userlist?activityid=' + this.activitId + '&award_Num=' + this.data.ActivityInfo.award_Num,
        });
    },
    // 显示遮罩层
    showshadow: function (param) {
        if (param.currentTarget.id == 'fenxiang') {
            this.setData({
                fenxiang: true,
            });
        }
        if (this.data.chooseSize == false) {
            this.chooseSezi();
        } else {
            this.hideModal();
        }
    },
    /**
     *
     * @param {下一个活动 animation动画} e
     */
    animationActivity: function (e) {
        this.openShow == true; //不是从服务通知进入的
        this.animationActivityMom = wx.createAnimation({
            duration: 500,
            timingFunction: 'linear',
        });
        this.animationActivityMom.opacity(1).step();
        this.setData({
            animationActivity: this.animationActivityMom.export(),
            SharePrize: false, //关闭分享
        });
        this.onReady();
        //隐藏
        setTimeout(
            function () {
                this.animationActivityMom.opacity(0).step();
                this.setData({
                    animationActivity: this.animationActivityMom.export(),
                });
            }.bind(this),
            100
        );

        //点击下一个活动 next
        new Request('Activity/ClickNextActivity').request(
            () => {
                return {
                    openid: app.globalData.openid, //用户openid
                    ActivityId: this.activitId, //活动详情列表id
                };
            },
            (res) => {
                if (!res.data.data == '') {
                    res.data.data.award_image = 'https://weizhi.darenjian.com' + res.data.data.award_image;
                    this.setData({
                        ActivityInfo: res.data.data,
                    });
                    this.activitId = res.data.data.id; //更新下一个奖品id
                    this.shuaxing(); //刷新当前值
                } else {
                    wx.showToast({
                        title: '没有下一个了',
                        icon: 'loading',
                        duration: 2000,
                    });
                }
                //显示
                setTimeout(
                    function () {
                        this.animationActivityMom.opacity(1).step();
                        this.setData({
                            animationActivity: this.animationActivityMom.export(),
                        });
                    }.bind(this),
                    1000
                );
            }
        );
    },
    // 动画函数
    chooseSezi: function (e) {
        // 用that取代this，防止不必要的情况发生
        var that = this;
        // 创建一个动画实例
        var animation = wx.createAnimation({
            // 动画持续时间
            duration: 500,
            // 定义动画效果，当前是匀速
            timingFunction: 'linear',
        });
        // 将该变量赋值给当前动画
        that.animation = animation;
        // 先在y轴偏移，然后用step()完成一个动画
        animation.translateY(1000).step();
        // 用setData改变当前动画
        that.setData({
            // 通过export()方法导出数据
            animationData: animation.export(),
            // 改变view里面的Wx：if
            chooseSize: true,
        });
        // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动 滑动时间
        setTimeout(function () {
            animation.translateY(0).step();
            that.setData({
                animationData: animation.export(),
                clearcart: false,
            });
        }, 100);
    },
    // 隐藏
    hideModal: function (e) {
        var that = this;
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'linear',
        });
        that.animation = animation;
        animation.translateY(700).step();
        that.setData({
            animationData: animation.export(),
        });
        setTimeout(function () {
            animation.translateY(0).step();
            that.setData({
                animationData: animation.export(),
                chooseSize: false,
            });
        }, 500);
    },
    //隐藏输入暗号透明层
    hideShowCodeBox: function () {
        this.AnHaoText = ''; //关闭弹窗清空暗号内容
        this.click = 1; //关闭显示按钮，重新计算按钮点击次数
        this.setData({
            ShowCodeBox: false,
        });
    },
    //隐藏首页推广按钮
    hideShowWechat: function () {
        this.setData({
            ShowWechat: false,
        });
    },
    //显示首页推广按钮
    _ShowWechat: function () {
        this.setData({
            ShowWechat: true,
        });
    },
    //显示首页推广
    _ShowTeam: function () {
        this.setData({
            ShowTeam: true,
        });
    },
    //隐藏首页推广按钮
    hideShowTeam: function () {
        this.setData({
            ShowTeam: false,
        });
    },
    /**
     * 点击复制 微信号
     */
    CopyWxHao: function () {
        wx.setClipboardData({
            data: 'pmliuyang003',
            success: (res) => {
                setTimeout(() => {
                    this.setData({
                        ShowWechat: false,
                        ShowTeam: false,
                    });
                }, 2001);
            },
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        //渲染抽奖详情
        if (this.openShow == true) {
            setTimeout(
                function () {
                    wx.createSelectorQuery()
                        .select('#Activity')
                        .boundingClientRect(
                            function (e) {
                                var height = e.height;
                                console.log('监听可用高度' + height);
                                console.log('窗口可用高度' + app.globalData.windowHeight);
                                console.log('状态栏可用高度' + app.globalData.statusBarHeight);
                                //初始化 记录数组
                                this.HeightArray = new Array();
                                // if(isNaN(height) || app.globalData.windowHeight >= height){
                                this.number = setInterval(() => {
                                    wx.createSelectorQuery()
                                        .select('#Activity')
                                        .boundingClientRect(
                                            function (res) {
                                                res.height = res.height;
                                                this.HeightArray.push(1);
                                                if (this.HeightArray.length == 15) {
                                                    clearInterval(this.number); //关闭 铺获
                                                }
                                                console.log(res.height);
                                                this.setData({
                                                    // ActivityHeight: res.height + 60,
                                                    backheight: res.height + 600 + 'px',
                                                });
                                            }.bind(this)
                                        )
                                        .exec();
                                }, 100);
                            }.bind(this)
                        )
                        .exec();
                }.bind(this),
                100
            );
        }
        //显示分享朋友圈按钮
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
            success(res) {},
        });
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // if(this.openShow == true){
        //   const eventChannel = this.getOpenerEventChannel();
        //   eventChannel.on('acceptDataFromOpenerPage', function(data) {
        //   });
        // }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        console.log('------------------------------------页面隐藏------------------------------------');
        //关闭 铺获
        clearInterval(this.number);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        //关闭 铺获
        clearInterval(this.number);
        console.log('------------------------------------监听页面卸载------------------------------------');
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    //跳转到发布页面
    _GoToPushAward: function (e) {
        wx.switchTab({
            url: '/pages/pushlotto/pushlotto',
        });
    },
    /**
     * 用户授权登陆
     */
    bindGetUserInfo(e) {
        console.log(e);
        //取消授权 执行不了此API方法
        wx.getUserInfo({
            success: (res) => {
                app.globalData.userInfo = res.userInfo;

                //注册用户
                if (app.globalData.loginStatus != true) {
                    //还没有授权登陆
                    new Request('Login/registerUser').request(
                        () => {
                            return {
                                openid: app.globalData.openid, //用户openid
                                userName: res.userInfo.nickName, //用户名
                                userAvatar: res.userInfo.avatarUrl, //用户头像
                                userCity: res.userInfo.city, //用户城市
                            };
                        },
                        (res) => {
                            console.log(res.data.msg);
                            console.log(app.globalData);
                            app.globalData.loginStatus = true; //用户授权登录 修改状态
                            this.setData({ loginStatus: true });
                        }
                    );
                } else {
                    //已经授权登陆了
                    this.setData({
                        loginStatus: true,
                    });
                }
            },
        });
        if (typeof e.detail.userInfo == 'undefined' || e.detail.userInfo == '') {
            //用点击了授权取消
            wx.showToast({
                title: '取消授权',
                icon: 'none',
                duration: 2000,
            });
        } else {
            console.log('授权了');
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        //显示分享朋友圈按钮
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
            success(res) {
                console.log(res);
            },
        });
        console.log(res);
        //用户点击 按钮分享活动
        if (res.from == 'button') {
            new Request('Share/UpdateShareApi').request(
                () => {
                    return {
                        openid: app.globalData.openid, //用户openid
                        ActivityId: this.activitId, //活动详情列表id
                    };
                },
                (res) => {
                    let activitId = { activitId: this.activitId };
                    this.onLoad(activitId);
                    this.hideModal();
                }
            );
            // 来自页面内转发按钮
            console.log(res.target);
            let shareTile = this.data.ActivityInfo.award_name; //活动奖品名字
            let shareId = this.activitId; //活动详情id
            let shareImage = this.data.ActivityInfo.award_image; //活动图片
            return {
                title: shareTile,
                path: '/pages/home/good_detail/good_detail?activitId=' + shareId,
                imageUrl: shareImage,
                success: (res) => {
                    console.log('转发成功', res);
                },
                fail: (res) => {
                    console.log('转发失败', res);
                },
            };
        }
    },
});
